// Copyright 2019 The rhyme_lph Authors. All rights reserved.
// Use of this source code is governed by a BSD-style license that can be
// found in the LICENSE file.
// s [author] rhyme_lph
// z [email]  rhymelph@gmail.com
// W [github] https://github.com/rhymelph

import 'package:base_plugin/base_plugin.dart';
import 'package:finance_app/src/common/app_spaces.dart';
import 'package:finance_app/src/entities/transaction_entity.dart';
import 'package:finance_app/src/provider/dashboard/credit_debit/credit_debit_provider.dart';
import 'package:finance_app/src/provider/dashboard/credit_debit/views/debit_note_provider.dart';
import 'package:finance_app/src/utils/date_time_utils.dart';
import 'package:finance_app/src/utils/form_utils.dart';
import 'package:finance_app/src/utils/language_utils.dart';
import 'package:finance_app/src/utils/transaction_type_utils.dart';
import 'package:finance_app/src/widgets/button/filter_button.dart';
import 'package:finance_app/src/widgets/button/normal_down_button.dart';
import 'package:finance_app/src/widgets/chip/normal_chip.dart';
import 'package:finance_app/src/widgets/dash_board/credit_note_item.dart';
import 'package:finance_app/src/widgets/dash_board/transaction_record_title_item.dart';
import 'package:finance_app/src/widgets/input/search_input_field.dart';
import 'package:flutter/material.dart';
import 'package:pull_to_refresh/pull_to_refresh.dart';
import 'package:tuple/tuple.dart';

class DebitNoteView extends StatefulWidget {
  @override
  _DebitNoteViewState createState() => _DebitNoteViewState();
}

class _DebitNoteViewState extends State<DebitNoteView>
    with
        StatefulPresenter<DebitNoteView, CreditDebitProvider,
            DebitNoteProvider>,
        KeepAliveMixin {
  @override
  Widget buildWidget(BuildContext context) => ColoredBox(
        color: Colors.white,
        child: Column(
          children: [
            AppSpaces.h20,
            SearchInputField(
              controller: provider.searchController,
              focusNode: provider.searchFocusNode,
            ),
            AppSpaces.h20,
            Row(
              mainAxisAlignment: MainAxisAlignment.spaceBetween,
              children: [
                _buildTimeSelect(),
                FilterButton(
                  onPressed: provider.onShowFilter,
                ),
              ],
            ),
            AppSpaces.h20,
            _buildFilterList(),
            Expanded(
                child: listBuilder<Tuple2<bool, List<TransactionEntity>>>(
              selector: (_, __) => Tuple2(
                  __.hasUp,
                  __.transactionList == null
                      ? null
                      : List.from(__.transactionList)),
              builder: (BuildContext context,
                      Tuple2<bool, List<TransactionEntity>> value,
                      Widget child) =>
                  SmartRefresher(
                controller: provider.refreshController,
                onRefresh: provider.onRefresh,
                onLoading: provider.onLoadMore,
                enablePullUp: value.item1,
                child: value.item2 == null
                    ? super.buildLoadingWidget(context)
                    : value.item2.length == 0
                        ? super.buildEmptyWidget(provider, context)
                        : ListView(
                            controller: provider.controller,
                            children: _buildTransactionList(),
                          ),
              ),
            ))
          ],
        ),
      );

  Widget _buildFilterList() {
    return listBuilder<int>(
        builder: (BuildContext context, int value, Widget child) => value == 0
            ? Container()
            : Container(
                height: getDp(30),
                margin: EdgeInsets.only(
                  bottom: getDp(5),
                ),
                alignment: Alignment.centerLeft,
                child: ListView.separated(
                  padding: EdgeInsets.symmetric(
                    horizontal: getDp(10),
                  ),
                  scrollDirection: Axis.horizontal,
                  shrinkWrap: true,
                  itemBuilder: (BuildContext context, int index) =>
                      value - 1 == index && provider.rangeTime != null
                          ? NormalChip(
                              title: provider.rangeTime,
                              onClose: provider.onClearRangeTime,
                            )
                          : _buildFilterItem(context, index),
                  itemCount: value,
                  separatorBuilder: (BuildContext context, int index) {
                    return Container(
                      width: getDp(15),
                    );
                  },
                ),
              ),
        selector: (_, __) => __.filterListLength);
  }

  Widget _buildFilterItem(BuildContext context, int index) {
    return listBuilder<String>(
        builder: (BuildContext context, String value, Widget child) =>
            NormalChip(
              title: LanguageUtils.translateFilter(value),
              onClose: () => provider.onRemoveFilter(value),
            ),
        selector: (_, __) => __.currentSelectFilterList[index]);
  }

  Widget _buildTimeSelect() {
    return listBuilder<String>(
        builder: (BuildContext context, String value, Widget child) =>
            NormalDownButton(
              title: value,
              onTap: provider.onSelectTime,
            ),
        selector: (_, __) => __.currentSelectTime);
  }

  List<Widget> _buildTransactionList() {
    List<Widget> child = [];
    for (final item in provider.transactionMap.entries) {
      child.add(TransactionRecordTitleItem(
        title: item.key,
      ));
      child.addAll(item.value.map((e) => CreditNoteItem(
            onTap: () => provider.onNavTransactionDetail(e),
            tag: TransactionTypeUtils.getTransactionType(e.transactionType),
            name: e.name,
            time: DateTimeUtils.formatDateTimeString(e.issuedAt),
            amount: e.total?.toDouble(),
            currency: e.currencyCode,
            billNumber: e.number,
            status: FormUtils.getStatus(
                TransactionTypeUtils.getTransactionTypeStatus(
                    e.transactionType),
                e.status,
                e.unpaid),
          )));
    }
    return child;
  }
}
